import { useEffect } from "react";
import {EditorFunctions} from "./TextEditorFunctions.tsx";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { LogicalSize } from '@tauri-apps/api/dpi';
import "./TextEditor.css";

function TextEditor() {
  const {
    isSaved,
    error,
    location,
    content,
    fileName,
    routeinforef,
    loadFileContent,
    saveFile,
    handleContentChange,
    handleFileNameChange,
    handleBack
  } = EditorFunctions();
  
  // 当组件加载时，从location state获取路径信息
  useEffect(() => {
    const route_info = {
      user : location.state.routeInfo.user,
      url : location.state.routeInfo.url,
    }
    routeinforef.current = route_info;
    if (location.state.name) {
      loadFileContent(location.state.filePath);
      console.log("file name is ", fileName);
    } 
    getCurrentWindow().setSize(new LogicalSize(1000, 600));
    console.log("Entered into editor.");
  }, []);

  return (
    <div className="text-editor">
      <div className="editor-header">
        <button id="back" onClick={handleBack}>🔙Return</button>
        <button id="save"
          onClick={saveFile} disabled={isSaved || !fileName || !content}>
          💾Save
        </button>
        <input
          title="File Name"
          type="text"
          placeholder="🙈File Name"
          value={fileName}
          onChange={handleFileNameChange}
          className="file-name-input"
        />
      </div>
      
      <textarea
        className="editor-content"
        value={content}
        onChange={handleContentChange}
        placeholder="🙉Type your content here..."
      />
      <div className="editor-status">
        {isSaved ? "✅ Saved" : "⚠️ Unsaved changes"}
        {error && <div id="error">{error}</div>}
      </div>
    </div>
  );
}

export default TextEditor;